#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <winsock2.h>
#include <windows.h>

#pragma comment(lib,"ws2_32.lib")

using namespace std;

const uint16_t SERVER_PORT = 8080;
string SERVER_IP = "43.139.5.31";

int main()
{
    WSADATA wsa;

    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("WSAStartup failed\n");
        return -1;
    }

    SOCKET sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == SOCKET_ERROR)
    {
        cout << "socket error " << endl;
        exit(-1);
    }

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(SERVER_IP.c_str());
    server.sin_port = htons(SERVER_PORT);


#define NUM 1024
    char inbuffer[NUM] = "";

    string masage;
    while (true)
    {
        cout << "请输入>: ";
        getline(cin, masage);

        int n = sendto(sockfd, masage.c_str(), masage.size(), 0, (struct sockaddr*)&server, sizeof(server));
        if (n < 0)
        {
            cerr << "send error " << endl;
            break;
        }

        inbuffer[0] = 0;

        struct sockaddr_in peer;
        int peerlen = sizeof(server);
        n = recvfrom(sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (sockaddr*)&peer, &peerlen);
        if (n > 0)
        {
            inbuffer[n] = 0;
            cout << "返回的消息是>: " << inbuffer << endl;
        }
        else
        {
            break;
        }
    }

    closesocket(sockfd);
    WSACleanup();

    return 0;
}